package com.ktwlrj.core.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;


/**
 * 后端http请求
 * @author lisc
 *
 */
public class HttpRequestUtils {
	/**
	 * http请求get方式
	 * @param httpurl
	 * @param param
	 * @return
	 */
	 public static String sendGet(String httpurl,Map<String,String> param) {
	        HttpURLConnection connection = null;
	        InputStream inStream = null;
	        BufferedReader bufferReader = null;
	        int successCode=200;
	     // 返回结果字符串
	        String result = null;
	        try {
	            // 创建远程url连接对象
	            URL url = new URL(httpurl);
	            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
	            connection = (HttpURLConnection) url.openConnection();
	            // 设置连接方式：get
	            connection.setRequestMethod("GET");
	            // 设置连接主机服务器的超时时间：15000毫秒
	            connection.setConnectTimeout(15000);
	            // 设置读取远程返回的数据时间：60000毫秒
	            connection.setReadTimeout(60000);
	            // 发送请求
	            connection.connect();
	            // 通过connection连接，获取输入流
	            if (connection.getResponseCode() == successCode) {
	            	inStream = connection.getInputStream();
	                // 封装输入流is，并指定字符集
	            	bufferReader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
	                // 存放数据
	                StringBuffer sBuffer= new StringBuffer();
	                String temp = null;
	                while ((temp = bufferReader.readLine()) != null) {
	                	sBuffer.append(temp);
	                }
	                result = sBuffer.toString();
	            }
	        } catch (MalformedURLException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            // 关闭资源
	            if (null != inStream) {
	                try {
	                	inStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	 
	            if (null != bufferReader) {
	                try {
	                	bufferReader.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if(connection!=null)
	            {
	            	// 关闭远程连接
		            connection.disconnect();
	            }

	        }
	 
	        return result;
	    }
	 
	   /**
	    * http请求post方式
	    * @param httpUrl
	    * @param param
	    * @return
	    */
	    public static String sendPost(String httpUrl, String param) {	 
	        HttpURLConnection connection = null;
	        InputStream inStream = null;
	        OutputStream outwritestream = null;
	        BufferedReader bufferReader = null;
	        String result = null;
	        int successCode=200;
	        try {
	            URL url = new URL(httpUrl);
	            // 通过远程url连接对象打开连接
	            connection = (HttpURLConnection) url.openConnection();
	            // 设置连接请求方式
	            connection.setRequestMethod("POST");
	            // 设置连接主机服务器超时时间：15000毫秒
	            connection.setConnectTimeout(15000);
	            // 设置读取主机服务器返回数据超时时间：60000毫秒
	            connection.setReadTimeout(60000);	 
	            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
	            connection.setDoOutput(true);
	            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
	            connection.setDoInput(true);
	            //设置通用请求属性
	            connection.setRequestProperty("Connection", "Keep-Alive");
	            connection.setRequestProperty("Charset", "UTF-8");
	            connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
	            connection.setRequestProperty("accept","application/json");
	            //发送json参数
	            byte[] parambytes =  param.getBytes(Charset.forName("UTF-8"));
	            connection.setRequestProperty("Content-Length", String.valueOf(parambytes.length));
	            outwritestream = connection.getOutputStream();
	            outwritestream.write(parambytes);	            
	            // 通过连接对象获取一个输入流，向远程读取
	            if (connection.getResponseCode() == successCode) {	 
	            	inStream = connection.getInputStream();
	                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
	            	bufferReader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
	                StringBuffer sBuffer = new StringBuffer();
	                String temp = null;
	                // 循环遍历一行一行读取数据
	                while ((temp = bufferReader.readLine()) != null) {
	                	sBuffer.append(temp);
	                }
	                result = sBuffer.toString();
	            }
	        } catch (MalformedURLException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            if (null != bufferReader) {
	                try {
	                	bufferReader.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (null != outwritestream) {
	                try {
	                	outwritestream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (null != inStream) {
	                try {
	                	inStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if(connection!=null)
	            {
		            connection.disconnect();
	            }
	        }
	        return result;
	    }
	    
	    /**
	     * 下载保存文件
	     * @param urlPath
	     * @param SavePath
	     */
	    public static String downAndSaveFile(String urlPath,String savePath,String fileName)
	    {
	    	//文件名称
	    	String newfileName=UUID.randomUUID().toString().replaceAll("-","")+fileName.substring(fileName.lastIndexOf("."));
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
	        String dateDir=dateFormat.format(new Date());
	        String newSavePath=savePath+"/"+dateDir;
	    	InputStream inputStream=null;
	    	OutputStream outpuStream=null;
	    	// 构造URL  
	    	try
	    	{
		        URL url = new URL(urlPath);  
		        // 打开连接  
		        URLConnection con = url.openConnection();  
		        //设置请求超时为5s  
		        con.setConnectTimeout(5*1000);  
		        // 输入流  
		        inputStream = con.getInputStream();  
		      
		        // 1K的数据缓冲  
		        byte[] fileByte = new byte[1024];  
		        // 读取到的数据长度  
		        int len;  
		        // 输出的文件流  
		        File fileDir=new File(newSavePath);  
		        if(!fileDir.exists()){  
		    	   boolean isMkdirs=fileDir.mkdirs();  
		    	   if(isMkdirs==false)
		    	   {
		    		   throw new IOException("文件目录创建失败");
		    	   }
		        }  
		        outpuStream = new FileOutputStream(fileDir.getPath()+"/"+newfileName);  
		        // 开始读取  
		        while ((len = inputStream.read(fileByte)) != -1) {  
		        	outpuStream.write(fileByte, 0, len);  
		        }  
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    	finally
	    	{
	            if (null != inputStream) {
	                try {
	                	inputStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (null != outpuStream) {
	                try {
	                	outpuStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	    	}
	    	return "/"+dateDir+"/"+newfileName;
	    }
}
